package engine;

import java.util.ArrayList;

public class Control {

	private ArrayList<EventObserver_IF<?>> observers = new ArrayList<EventObserver_IF<?>>();
	private ArrayList<EventProcessor_IF> processors = new ArrayList<EventProcessor_IF>();
	private ArrayList<View> views = new ArrayList<View>();
	private Game game;
	private Thread gameThread = null;
	private volatile boolean isRunning = true;

	public Control(Game game) {
		this.game = game;
	}

	public void run() {
		if (gameThread == null)
			gameThread = new Thread() {
				@Override
				public void run() {
					while (true)
						while (isRunning) {
							handleEvents();
							game.step();
							updateViews();
							try {
								sleep(1000 / game.getGameRate());
							} catch (InterruptedException e) {}
						}
				}
			};
		gameThread.run();
	}

	public void resume() {
		isRunning = true;
	}

	public void suspend() {
		isRunning = false;
	}

	private synchronized void handleEvents() {
		for (EventObserver_IF<?> observer : observers) {
			ArrayList<?> events = observer.getEvents();
			for (EventProcessor_IF processor : processors)
				for (Object event : events)
					processor.handleEvent(event, game);
		}
	}

	private synchronized void updateViews() {
		for (View view : views)
			view.update(game);
	}

	public void addObserver(EventObserver_IF<?> observer) {
		observers.add(observer);
	}

	public void removeObserver(EventObserver_IF<?> observer) {
		observers.remove(observer);
		{}
	}

	public void removeAllObservers() {
		observers.clear();
	}

	public void addProcessor(EventProcessor_IF processor) {
		processors.add(processor);
	}

	public void removeProcessor(EventProcessor_IF processor) {
		processors.remove(processor);
	}

	public void removeAllProcessor() {
		processors.clear();
	}

	public void addView(View view) {
		views.add(view);
	}

	public void removeView(View view) {
		views.remove(view);
	}

	public void removeAllViews() {
		views.clear();
	}
}
